package com.cibfintech.rpa.jdwzcx.service;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Future;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import com.cibfintech.rpa.jdwzcx.common.dto.SearchResult;
import com.cibfintech.rpa.jdwzcx.common.manager.CaptchaManager;

@Component
public class JdwzcxWebRunner {

    @Autowired
    private CaptchaManager captchaManager;

    @Async
    public Future<SearchResult> shixinCsrc(String name) throws IOException {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("disable-infobars");
        WebDriver driver = new ChromeDriver(options);
        driver.manage().window().maximize();

        driver.get("http://shixin.csrc.gov.cn/honestypub/");
        boolean warn = false;

        WebElement objName = driver.findElement(By.id("objName"));
        objName.clear();
        objName.sendKeys(name);

        WebElement captchaImg = driver.findElement(By.id("captcha_img"));
        captchaImg.click();
        Point location = captchaImg.getLocation();
        Dimension size = captchaImg.getSize();
        byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
        BufferedImage img = ImageIO.read(new ByteArrayInputStream(screenshot));
        BufferedImage dest = img.getSubimage(location.getX(), location.getY(), size.getWidth(), size.getHeight());
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ImageIO.write(dest, "png", output);
        byte[] byteArr = output.toByteArray();

        String captcha = captchaManager.recognize(byteArr, 5);
        driver.findElement(By.id("ycode")).sendKeys(captcha);
        driver.findElement(By.id("querybtn")).click();

        boolean checkError = false;
        String checkerrorString;
        try {
            checkerrorString = driver.findElement(By.xpath("//*[@id=\"list_form\"]/table/tbody/tr[1]/td/table/tbody/tr[3]/td[4]")).getText();
            if (StringUtils.contains(checkerrorString, "验证码错误"))
                checkError = true;
        } catch (NoSuchElementException e) {
            checkError = false;
        }

        while (checkError) {
            driver.findElement(By.id("objName")).sendKeys(name);
            screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
            img = ImageIO.read(new ByteArrayInputStream(screenshot));
            dest = img.getSubimage(location.getX(), location.getY(), size.getWidth(), size.getHeight());
            output = new ByteArrayOutputStream();
            ImageIO.write(dest, "png", output);
            byteArr = output.toByteArray();
            captcha = captchaManager.recognize(byteArr, 5);
            driver.findElement(By.id("ycode")).sendKeys(captcha);
            driver.findElement(By.id("querybtn")).click();
            try {
                checkerrorString = driver.findElement(By.xpath("//*[@id=\"list_form\"]/table/tbody/tr[1]/td/table/tbody/tr[3]/td[4]")).getText();
                if (StringUtils.contains(checkerrorString, "验证码错误"))
                    checkError = true;
            } catch (NoSuchElementException e) {
                checkError = false;
            }
        }

        try {
            driver.findElement(By.xpath("//*[@id=\"sorttab2\"]/tbody/tr/td[5]/a/img")).click();
            Object[] handleArray = driver.getWindowHandles().toArray();
            driver.switchTo().window(handleArray[1].toString());
            warn = true;
        } catch (NoSuchElementException e) {
        }
        String base64Png = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);
        driver.quit();
        SearchResult result = new SearchResult();
        result.setWarn(warn);
        result.setBase64Png(base64Png);
        return new AsyncResult<SearchResult>(result);
    }

    @Async
    public Future<SearchResult> hdChinatax(String name, String type) throws IOException {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("disable-infobars");
        WebDriver driver = new ChromeDriver(options);
        driver.manage().window().maximize();

        driver.get("http://hd.chinatax.gov.cn/xxk/");
        boolean warn = false;

        if (StringUtils.equals(type, "自然人"))
            driver.findElements(By.id("categeryid")).get(1).click();

        driver.findElement(By.id("queryvalue")).sendKeys(name);
        driver.findElement(
                By.xpath("/html/body/table[1]/tbody/tr/td[3]/table[2]/tbody/tr[1]/td/form/table/tbody/tr/td/table[3]/tbody/tr/td[1]/table/tbody/tr/td/a"))
                .click();

        driver.switchTo().frame("rightiframe");
        WebElement tbody = driver.findElement(By.xpath("//*[@id=\"searchForm\"]/table[2]/tbody"));
        List<WebElement> trlist = tbody.findElements(By.tagName("tr"));

        if (trlist.size() > 1) {
            trlist.get(1).findElement(By.tagName("a")).click();
            warn = true;
        }

        String base64Png = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);

        driver.quit();
        SearchResult result = new SearchResult();
        result.setWarn(warn);
        result.setBase64Png(base64Png);

        return new AsyncResult<SearchResult>(result);
    }

    @Async
    public Future<SearchResult> zhixingCourt(String name, String cardNumber) throws Exception {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("disable-infobars");
        WebDriver driver = new ChromeDriver(options);
        driver.manage().window().maximize();

        driver.get("http://zhixing.court.gov.cn/search/");
        boolean warn = false;

        driver.findElement(By.id("pName")).sendKeys(name);
        driver.findElement(By.id("pCardNum")).sendKeys(cardNumber);

        WebElement captchaImg = driver.findElement(By.id("captchaImg"));
        captchaImg.click();
        Thread.sleep(3000);
        Point location = captchaImg.getLocation();
        Dimension size = captchaImg.getSize();
        byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
        BufferedImage img = ImageIO.read(new ByteArrayInputStream(screenshot));
        BufferedImage dest = img.getSubimage(location.getX(), location.getY(), size.getWidth(), size.getHeight());
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ImageIO.write(dest, "png", output);
        byte[] byteArr = output.toByteArray();

        String captcha = captchaManager.recognize(byteArr);
        driver.findElement(By.id("yzm")).sendKeys(captcha);
        Thread.sleep(3000);
        String display = driver.findElement(By.xpath("//*[@id=\"yzm-group\"]/div[4]")).getCssValue("display");
        while (!StringUtils.equals(display, "none")) {
            captchaImg.click();
            Thread.sleep(3000);
            screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
            img = ImageIO.read(new ByteArrayInputStream(screenshot));
            dest = img.getSubimage(location.getX(), location.getY(), size.getWidth(), size.getHeight());
            output = new ByteArrayOutputStream();
            ImageIO.write(dest, "png", output);
            byteArr = output.toByteArray();
            captcha = captchaManager.recognize(byteArr);
            driver.findElement(By.id("yzm")).clear();
            driver.findElement(By.id("yzm")).sendKeys(captcha);
            Thread.sleep(3000);
            display = driver.findElement(By.xpath("//*[@id=\"yzm-group\"]/div[4]")).getCssValue("display");
        }

        driver.findElement(By.xpath("//*[@id=\"yzm-group\"]/div[6]/button")).click();
        Thread.sleep(3000);

        try {
            driver.findElement(By.xpath("//*[@id=\"tbody-result\"]/p"));
        } catch (NoSuchElementException e) {
            warn = true;
        }

        String base64Png = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);

        driver.quit();
        SearchResult result = new SearchResult();
        result.setWarn(warn);
        result.setBase64Png(base64Png);
        return new AsyncResult<SearchResult>(result);
    }

    @Async
    public Future<SearchResult> websearchMee(String name) {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("disable-infobars");
        WebDriver driver = new ChromeDriver(options);
        driver.manage().window().maximize();

        driver.get("http://www.mee.gov.cn/");
        boolean warn = false;

        driver.findElement(By.id("searchword")).sendKeys(name);
        driver.findElement(By.xpath("//*[@id=\"form2\"]/div[1]/input[3]")).submit();

        String base64Png = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);

        driver.quit();
        SearchResult result = new SearchResult();
        result.setWarn(warn);
        result.setBase64Png(base64Png);
        return new AsyncResult<SearchResult>(result);
    }

}
